<?php
/* Script is meant for opening session from communicator and create user
   if provide id is used for a first time.
   
   GET parameters:
      - username
      
   Return values:
      - session id
      - panding messages 
      
      
*/

require_once './common/header.php';

// Get provided 'userid' parameter. Id does not exist, return error message and finish.
$username = $_GET['username'];
if ($username == "")
{
   OutputError('Username has not been provided');
   exit(1);
}

// Check if given username exists, if not create user and session and return it.
// If user does exists: @TODO - send response to provide user's password to create
// additional session for this user (i.e. communicator runs on pc and mobile).
$query = "SELECT id FROM users WHERE username='" . mysql_real_escape_string($username) . "'";
$reader = $db->SelectScalar($query);
if ($reader === false)
{
   // Create new user in database.
   $query = 'INSERT INTO users (username, last_activity) VALUES (' . 
      "'" . mysql_real_escape_string($username) . "'," .
      'FROM_UNIXTIME(' . time() . '))';
   
   $user_id = $db->Insert($query);
   if ($user_id == -1)
   {
      OutputError('Cannot create new user');
      exit(1);
   }
   
   // User has been added, create new session.
   $session_id = GenRandomString(50);
   $query = 'INSERT INTO user_sessions VALUES (' . 
      $user_id . ',' .
      "'$session_id'," .
      'FROM_UNIXTIME(' . time() . '))';
   if ($db->Insert($query) == -1)
   {
      // @TODO: delete user, create transation for whole action
      OutputError('Cannot create new user');
      exit(1);
   }
   
   // User and session created, return session in response.
   print('$session_id\n');
}
   
require_once './common/footer.php';

?>